/**
  ******************************************************************************
  * File Name          : stm32f1xx_uart.c
  * Description        : This file provides code for the MSP Initialization 
  *                      and de-Initialization codes.
  ******************************************************************************
  *
  * COPYRIGHT(c) 2016 STMicroelectronics
  *
  * Redistribution and use in source and binary forms, with or without modification,
  * are permitted provided that the following conditions are met:
  *   1. Redistributions of source code must retain the above copyright notice,
  *      this list of conditions and the following disclaimer.
  *   2. Redistributions in binary form must reproduce the above copyright notice,
  *      this list of conditions and the following disclaimer in the documentation
  *      and/or other materials provided with the distribution.
  *   3. Neither the name of STMicroelectronics nor the names of its contributors
  *      may be used to endorse or promote products derived from this software
  *      without specific prior written permission.
  *
  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  *
  ******************************************************************************
  */
/* Includes ------------------------------------------------------------------*/
#include <stdlib.h>
#include <math.h>
#include "stm32f1xx.h"
#include "stm32f1xx_hal.h"
#include "stm32f1xx_appevent.h"
#include "stm32f1xx_uart.h"
#include "stm32f1xx_flash.h"

#include <string.h>

static const uint8_t auchCRCHi[] = {
  0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 
  0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
  0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 
  0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 
  0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 
  0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 
  0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 
  0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 
  0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 
  0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 
  0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 
  0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 
  0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 
  0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 
  0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
  0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40
};

static const uint8_t auchCRCLo[] = {
  0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2, 0xC6, 0x06, 0x07, 0xC7, 0x05, 0xC5, 0xC4, 0x04, 
  0xCC, 0x0C, 0x0D, 0xCD, 0x0F, 0xCF, 0xCE, 0x0E, 0x0A, 0xCA, 0xCB, 0x0B, 0xC9, 0x09, 0x08, 0xC8, 
  0xD8, 0x18, 0x19, 0xD9, 0x1B, 0xDB, 0xDA, 0x1A, 0x1E, 0xDE, 0xDF, 0x1F, 0xDD, 0x1D, 0x1C, 0xDC, 
  0x14, 0xD4, 0xD5, 0x15, 0xD7, 0x17, 0x16, 0xD6, 0xD2, 0x12, 0x13, 0xD3, 0x11, 0xD1, 0xD0, 0x10, 
  0xF0, 0x30, 0x31, 0xF1, 0x33, 0xF3, 0xF2, 0x32, 0x36, 0xF6, 0xF7, 0x37, 0xF5, 0x35, 0x34, 0xF4, 
  0x3C, 0xFC, 0xFD, 0x3D, 0xFF, 0x3F, 0x3E, 0xFE, 0xFA, 0x3A, 0x3B, 0xFB, 0x39, 0xF9, 0xF8, 0x38, 
  0x28, 0xE8, 0xE9, 0x29, 0xEB, 0x2B, 0x2A, 0xEA, 0xEE, 0x2E, 0x2F, 0xEF, 0x2D, 0xED, 0xEC, 0x2C, 
  0xE4, 0x24, 0x25, 0xE5, 0x27, 0xE7, 0xE6, 0x26, 0x22, 0xE2, 0xE3, 0x23, 0xE1, 0x21, 0x20, 0xE0, 
  0xA0, 0x60, 0x61, 0xA1, 0x63, 0xA3, 0xA2, 0x62, 0x66, 0xA6, 0xA7, 0x67, 0xA5, 0x65, 0x64, 0xA4, 
  0x6C, 0xAC, 0xAD, 0x6D, 0xAF, 0x6F, 0x6E, 0xAE, 0xAA, 0x6A, 0x6B, 0xAB, 0x69, 0xA9, 0xA8, 0x68, 
  0x78, 0xB8, 0xB9, 0x79, 0xBB, 0x7B, 0x7A, 0xBA, 0xBE, 0x7E, 0x7F, 0xBF, 0x7D, 0xBD, 0xBC, 0x7C, 
  0xB4, 0x74, 0x75, 0xB5, 0x77, 0xB7, 0xB6, 0x76, 0x72, 0xB2, 0xB3, 0x73, 0xB1, 0x71, 0x70, 0xB0,
  0x50, 0x90, 0x91, 0x51, 0x93, 0x53, 0x52, 0x92, 0x96, 0x56, 0x57, 0x97, 0x55, 0x95, 0x94, 0x54, 
  0x9C, 0x5C, 0x5D, 0x9D, 0x5F, 0x9F, 0x9E, 0x5E, 0x5A, 0x9A, 0x9B, 0x5B, 0x99, 0x59, 0x58, 0x98, 
  0x88, 0x48, 0x49, 0x89, 0x4B, 0x8B, 0x8A, 0x4A, 0x4E, 0x8E, 0x8F, 0x4F, 0x8D, 0x4D, 0x4C, 0x8C,
  0x44, 0x84, 0x85, 0x45, 0x87, 0x47, 0x46, 0x86, 0x82, 0x42, 0x43, 0x83, 0x41, 0x81, 0x80, 0x40
};
static const uint8_t c_speed_modbus[] = {0x07,0xF5,0x08,0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07};
//static const uint8_t c_speed_modbusrsp[] = "Switch to Modbus Mode";
static const uint8_t c_version[]={0x00,10,19,0x00,0x02,0x00,7};
static const uint8_t c_ver_num = sizeof(c_version)/sizeof(c_version[0]);
/* Extern variables ----------------------------------------------------------*/
extern UART_HandleTypeDef huart1;//GSM
extern UART_HandleTypeDef huart2;//BLE
extern UART_HandleTypeDef huart3;//Bus
extern UART_HandleTypeDef huart4;//Speed
extern UART_HandleTypeDef huart5;//Level
extern uint32_t gSystemTick;

uint8_t gGsmRecByte;
uint8_t gBleRecByte;
uint8_t gBusRecByte;
uint8_t gSpeedRecByte;
uint8_t gLevelRecByte;

uart_t gGsmRecBuf;
uart_t gBleRecBuf;
uart_t gBusRecBuf;
uart_t gSpeedRecBuf;
uart_t gLevelRecBuf;
//uart Period
uartflag_t gUartFlag;
uartperiod_t gUartCnt;
//Canel
canel_t gCanelParam;
uint32_t gCanelArea;
//Device information
devInfo_t gDevInfo;
//uint32_t gChannelSpeed;
//uint32_t gChannelLevel;
//Flow
double gSumFlow = 0;
//
speed_t gSetSpeed;
setSpeed_t gReadSpeed;
writeSpeed_t gWriteSpeed;


//char BuidDate[] = __DATE__ ";

static void HAL_Gsm_ClearBuf(void);
static void HAL_Ble_ClearBuf(void);
static void HAL_Bus_ClearBuf(void);
static void HAL_Speed_ClearBuf(void);
static void HAL_Level_ClearBuf(void);

static uint16_t HalUartCalcCrc16( uint8_t *msg_ptr, uint8_t len );
//BLE
static void BLE_ProcessRecData(uint8_t *pBuf);
static void BLE_ProcessSendData(uint8_t cmd, uint8_t len, uint8_t *pBuf);
static uint8_t BLE_UartCalcFCS( uint8_t *msg_ptr, uint8_t len );
//static uint8_t MT_UartCalcFCS( uint8_t *msg_ptr, uint8_t len );
//static void HAL_UART_CmdACK(uint8_t layer, uint16_t cid, uint8_t cmd);
static void ModBus_SpeedSwitchToModBus(void);
static void ModBus_CalculateFlow(void);
static void ModBus_ReadRegister(uint8_t addr, uint8_t cmd, uint16_t regAddr, uint8_t num, uint8_t dev);
static void ModBus_WriteHoldingReg(uint8_t addr, uint16_t regAddr, uint16_t dat, uint8_t dev);
static void ModBus_ProcessReadRegister(uint8_t *pBuf);
static uint8_t ModBus_ProcessWriteRegister(uint8_t *pBuf);

extern void MX_USART3_UART_Init(uint8_t baudrate);
/* USER CODE BEGIN 0 */
/**
  * Initializes the Global MSP.
  */
static void uart_delay(uint16_t del)
{
  uint32_t tickstart = HAL_GetTick();
  
  while((HAL_GetTick()-tickstart) < del);
}
/**
  * @brief zigbee initinal
  * @param huart: UART handle.
  * @retval None
  */
void HAL_UART_Initinal(void)
{
  uint8_t tmpBuf[4];
  
  //Read Device Information
  Flash_ReadSystemInformation(SYSTEM_DEVICE_FLOW_OFFSET, SYSTEM_DEVICE_FLOW_SIZE, (uint8_t *)tmpBuf);
  if((tmpBuf[0] == 0xFF)&&(tmpBuf[1] == 0xFF)&&(tmpBuf[1] == 0xFF)&&(tmpBuf[2] == 0xFF))gWaterSumFlow = 0;
  else memcpy((uint8_t *)&gWaterSumFlow, tmpBuf, 4);
  gSumFlow = gWaterSumFlow;
  
  Flash_ReadSystemInformation(SYSTEM_DEVICE_INFO_OFFSET, SYSTEM_DEVICE_INFO_SIZE, (uint8_t *)&gDevInfo);
  if(gDevInfo.addr >= 0xFE)gDevInfo.addr = 0x01;
  if(gDevInfo.baudrate > C_BAUDRATE_115200)gDevInfo.baudrate = C_BAUDRATE_9600;
  
  Flash_ReadSystemInformation(SYSTEM_DEVICE_CANEL_OFFSET, SYSTEM_DEVICE_CANEL_SIZE, (uint8_t *)&gCanelParam);
  if(gCanelParam.mode > C_CANEL_AREA){
    gCanelParam.mode = C_CANEL_RECTANGLE;
    gCanelParam.radius = 0;
    gCanelParam.area = 0;
    gCanelParam.depth = 0;
    gCanelParam.recWide = 0;
    gCanelParam.trapeDown = 0;
    gCanelParam.trapeUp = 0;
  }
  
  Flash_ReadSystemInformation(SYSTEM_DEVICE_RANGE_OFFSET, SYSTEM_DEVICE_RANGE_SIZE, (uint8_t *)tmpBuf);
  if((tmpBuf[0]==0xFF)&&(tmpBuf[1] == 0xFF)){
    gWaterFirstLevel = 0;
  }
  else{
    gWaterFirstLevel = BUILD_UINT16(tmpBuf[1],tmpBuf[0]);
  }
  if((tmpBuf[2]==0xFF)&&(tmpBuf[3] == 0xFF)){
    gMeterRange = 0;
  }
  else{
    gMeterRange = BUILD_UINT16(tmpBuf[3],tmpBuf[2]);
  }
  
  Flash_ReadSystemInformation(SYSTEM_DEVICE_LOWRANGE_OFFSET, SYSTEM_DEVICE_LOWRANGE_SIZE, (uint8_t *)&gMeterLowRange);
  if(gMeterLowRange == 0xFFFF)gMeterLowRange = 0;
  
  Flash_ReadSystemInformation(SYSTEM_DEVICE_TOLERANCE_OFFSET, SYSTEM_DEVICE_TOLERANCE_SIZE, (uint8_t *)&gFlowTolerance); 
  if(gFlowTolerance == 0xFFFF)gFlowTolerance = 0;
  
  Flash_ReadSystemInformation(SYSTEM_DEVICE_MIN_SPEED_OFFSET, SYSTEM_DEVICE_MIN_SPEED_SIZE, (uint8_t *)&gWaterMinSpeed); 
  if(gWaterMinSpeed == 0xFFFF)gWaterMinSpeed = C_SPEED_MIN;
  
  Flash_ReadSystemInformation(SYSTEM_DEVICE_SETSPEED_OFFSET, SYSTEM_DEVICE_SETSPEED_SIZE, (uint8_t *)&gSetSpeed); 
  if(gSetSpeed.valid > 1)gSetSpeed.valid = 0;  
  
  MX_USART3_UART_Init(gDevInfo.baudrate);
  
  gGsmRecBuf.rxIdx = 0;
  HAL_UART_Receive_IT(&huart1, &gGsmRecByte, 1);
  
  gBleRecBuf.rxIdx = 0;
  HAL_UART_Receive_IT(&huart2, &gBleRecByte, 1);
  
  gBusRecBuf.rxIdx = 0;
  HAL_UART_Receive_IT(&huart3, &gBusRecByte, 1);
  
  gSpeedRecBuf.rxIdx = 0;
  HAL_UART_Receive_IT(&huart4, &gSpeedRecByte, 1);
  
  gLevelRecBuf.rxIdx = 0;
  HAL_UART_Receive_IT(&huart5, &gLevelRecByte, 1);
  
  gUartFlag.modbus = 0;
  
}
/**
  * @brief Rx Transfer completed callback.
  * @param huart: UART handle.
  * @retval None
  */
void HAL_UART1_RxCpltCallback(UART_HandleTypeDef *huart)
{
  gGsmRecBuf.rxBuf[gGsmRecBuf.rxIdx++] = gGsmRecByte;
  gGsmRecBuf.recData = TRUE;
  gGsmRecBuf.timeout = 0;
  
  if(gGsmRecBuf.rxIdx >= HAL_UART_BUF_SIZE)
  {
    gGsmRecBuf.rxIdx = 0;
  }
  HAL_UART_Receive_IT(&huart1, &gGsmRecByte, 1);
}
/**
  * @brief Rx Transfer completed callback.
  * @param huart: UART handle.
  * @retval None
  */
void HAL_UART2_RxCpltCallback(UART_HandleTypeDef *huart)
{
  gBleRecBuf.rxBuf[gBleRecBuf.rxIdx++] = gBleRecByte;
  gBleRecBuf.recData = TRUE;
  gBleRecBuf.timeout = 0;
  
  if(gBleRecBuf.rxIdx >= HAL_UART_BUF_SIZE)
  {
    gBleRecBuf.rxIdx = 0;
  }
  HAL_UART_Receive_IT(&huart2, &gBleRecByte, 1);
}
/**
  * @brief Rx Transfer completed callback.
  * @param huart: UART handle.
  * @retval None
  */
void HAL_UART3_RxCpltCallback(UART_HandleTypeDef *huart)
{
  gBusRecBuf.rxBuf[gBusRecBuf.rxIdx++] = gBusRecByte;
  gBusRecBuf.recData = TRUE;
  gBusRecBuf.timeout = 0;
  
  if(gBusRecBuf.rxIdx >= HAL_UART_BUF_SIZE)
  {
    gBusRecBuf.rxIdx = 0;
  }
  HAL_UART_Receive_IT(&huart3, &gBusRecByte, 1);
}
/**
  * @brief Rx Transfer completed callback.
  * @param huart: UART handle.
  * @retval None
  */
void HAL_UART4_RxCpltCallback(UART_HandleTypeDef *huart)
{
  gSpeedRecBuf.rxBuf[gSpeedRecBuf.rxIdx++] = gSpeedRecByte;
  gSpeedRecBuf.recData = TRUE;
  gSpeedRecBuf.timeout = 0;
  
  if(gSpeedRecBuf.rxIdx >= HAL_UART_BUF_SIZE)
  {
    gSpeedRecBuf.rxIdx = 0;
  }
  HAL_UART_Receive_IT(&huart4, &gSpeedRecByte, 1);
}
/**
  * @brief Rx Transfer completed callback.
  * @param huart: UART handle.
  * @retval None
  */
void HAL_UART5_RxCpltCallback(UART_HandleTypeDef *huart)
{
  gLevelRecBuf.rxBuf[gLevelRecBuf.rxIdx++] = gLevelRecByte;
  gLevelRecBuf.recData = TRUE;
  gLevelRecBuf.timeout = 0;
  
  if(gLevelRecBuf.rxIdx >= HAL_UART_BUF_SIZE)
  {
    gLevelRecBuf.rxIdx = 0;
  }
  HAL_UART_Receive_IT(&huart5, &gLevelRecByte, 1);
}
/**
  * @brief Clear Gsm Buffer Parameter
  * @param huart: None
  * @retval None
  */
static void HAL_Gsm_ClearBuf(void)
{
  gGsmRecBuf.rxIdx = 0;
  gGsmRecBuf.recData = FALSE;
  memset(gGsmRecBuf.rxBuf, 0, HAL_UART_BUF_SIZE);
}
/**
  * @brief Clear BLE Buffer Parameter
  * @param huart: None
  * @retval None
  */
static void HAL_Ble_ClearBuf(void)
{
  gBleRecBuf.rxIdx = 0;
  gBleRecBuf.recData = FALSE;
  memset(gBleRecBuf.rxBuf, 0, HAL_UART_BUF_SIZE);
}
/**
  * @brief Clear Bus Buffer Parameter
  * @param huart: None
  * @retval None
  */
static void HAL_Bus_ClearBuf(void)
{
  gBusRecBuf.rxIdx = 0;
  gBusRecBuf.recData = FALSE;
  memset(gBusRecBuf.rxBuf, 0, HAL_UART_BUF_SIZE);
}
/**
  * @brief Clear Speed Buffer Parameter
  * @param huart: None
  * @retval None
  */
static void HAL_Speed_ClearBuf(void)
{
  gSpeedRecBuf.rxIdx = 0;
  gSpeedRecBuf.recData = FALSE;
  memset(gSpeedRecBuf.rxBuf, 0, HAL_UART_BUF_SIZE);
}
/**
  * @brief Clear Level Buffer Parameter
  * @param huart: None
  * @retval None
  */
static void HAL_Level_ClearBuf(void)
{
  gLevelRecBuf.rxIdx = 0;
  gLevelRecBuf.recData = FALSE;
  memset(gLevelRecBuf.rxBuf, 0, HAL_UART_BUF_SIZE);
}
/**
  * @brief Process ZigBee command
  * @param huart: UART handle.
  * @retval None
  */
void HAL_UART_Preiod(void)
{
  //Uart Period
  gUartCnt.time100msCnt++;
  if(gUartCnt.time100msCnt >= 100){
    gUartCnt.time100msCnt = 0;
    gUartFlag.time100ms = 1;
    
    gUartCnt.time500msCnt++;
    if(gUartCnt.time500msCnt >= 5){
      gUartCnt.time500msCnt = 0;
      SET_BIT(gAppEvent, APPEVENT_GET_SPEED_EVT);
    }
    gUartCnt.time1sCnt++;
    if(gUartCnt.time1sCnt >= 10){
      gUartCnt.time1sCnt = 0;
//      SET_BIT(gAppEvent, APPEVENT_CALCULATE_EVT);
//      SET_BIT(gAppEvent, APPEVENT_GET_SPEED_EVT);
      SET_BIT(gAppEvent, APPEVENT_GET_LEVEL_EVT);
    }
    
    gUartCnt.time5sCnt++;
    if(gUartCnt.time5sCnt >= 50){
      gUartCnt.time5sCnt = 0;
      gUartFlag.time5s = 1;
    }
  }

  //GSM
  gGsmRecBuf.timeout++;
  if((gGsmRecBuf.recData == TRUE)&&(gGsmRecBuf.timeout > 20))
  {
    gGsmRecBuf.recData = FALSE;
    gGsmRecBuf.rxLen = gGsmRecBuf.rxIdx;
    SET_BIT(gAppEvent, APPEVENT_REC_GSM_EVT);
  }
  //BLE or RS232
  gBleRecBuf.timeout++;
  if((gBleRecBuf.recData == TRUE)&&(gBleRecBuf.timeout > 20))
  {
    gBleRecBuf.recData = FALSE;
    gBleRecBuf.rxLen = gBleRecBuf.rxIdx;
    SET_BIT(gAppEvent, APPEVENT_REC_BLE_EVT);
  }
  //Bus
  gBusRecBuf.timeout++;
  if((gBusRecBuf.recData == TRUE)&&(gBusRecBuf.timeout > 20))
  {
    gBusRecBuf.recData = FALSE;
    gBusRecBuf.rxLen = gBusRecBuf.rxIdx;
    SET_BIT(gAppEvent, APPEVENT_REC_BUS_EVT);
  }
  //flow speed
  gSpeedRecBuf.timeout++;
  if((gSpeedRecBuf.recData == TRUE)&&(gSpeedRecBuf.timeout > 20))
  {
    gSpeedRecBuf.recData = FALSE;
    gSpeedRecBuf.rxLen = gSpeedRecBuf.rxIdx;
    SET_BIT(gAppEvent, APPEVENT_REC_SPEED_EVT);
  }
  //Water Level
  gLevelRecBuf.timeout++;
  if((gLevelRecBuf.recData == TRUE)&&(gLevelRecBuf.timeout > 20))
  {
    gLevelRecBuf.recData = FALSE;
    gLevelRecBuf.rxLen = gLevelRecBuf.rxIdx;
    SET_BIT(gAppEvent, APPEVENT_REC_LEVEL_EVT);
  }
}
/**
  * @brief Process Bus command
  * @param huart: UART handle.
  * @retval None
  */
void HAL_UART_ProcessCmd(void)
{
  uint16_t tmpCrc;
  uint8_t tmpNum=0;
  float tmpSpeed;
  uint8_t tmpBuf[32];
  
  //Calculate
  if(gAppEvent & APPEVENT_CALCULATE_EVT){
    ModBus_CalculateFlow();
    gAppEvent ^= APPEVENT_CALCULATE_EVT;
  }
  //Read Speed
  if(gAppEvent & APPEVENT_GET_SPEED_EVT){//Process Speed
    //each 500ms
    if(gUartFlag.modbus == 0){
      gUartFlag.modbus = 1;
      ModBus_SpeedSwitchToModBus();
    }
    else{
      if(gReadSpeed.idx == 0){
        gReadSpeed.addr = REG_SPEED_WRITE;
        if(gWriteSpeed.flag){
          gWriteSpeed.flag = 0;
          ModBus_WriteHoldingReg(C_DEV_SPEED_ADDR, gWriteSpeed.addr, gWriteSpeed.dat, DEV_SPEED);
        }
      }
      else if(gReadSpeed.idx == 1){//Read Speed
        gReadSpeed.addr = REG_SURFACE_SPEED;
        tmpNum = 2;
      }
      else if(gReadSpeed.idx == 2){
        gReadSpeed.addr = REG_SPEED_SENSITIVITY;
        tmpNum = 1;
      }
      else if(gReadSpeed.idx == 3){
        gReadSpeed.addr = REG_SPEED_ANGLE;
        tmpNum = 1;
      }
      else if(gReadSpeed.idx == 4){
        gReadSpeed.addr = REG_SPEED_GAIN;
        tmpNum = 1;
      }
      else if(gReadSpeed.idx == 5){
        gReadSpeed.addr = REG_SPEED_POWER;
        tmpNum = 1;
      }
      else if(gReadSpeed.idx == 6){
        gReadSpeed.addr = REG_FLOW_DIERECTION;
        tmpNum = 1;
      }
      else if(gReadSpeed.idx == 7){
        gReadSpeed.addr = REG_STRENGTH_SPEED;
        tmpNum = 1;
      }
      else if(gReadSpeed.idx == 8){
        gReadSpeed.addr = REG_SPEED_VERSION;
        tmpNum = 4;
      }
      gReadSpeed.idx++;
      if(gReadSpeed.idx > 8){
        gReadSpeed.idx = 0;
      }
      if(tmpNum != 0){
        ModBus_ReadRegister(C_DEV_SPEED_ADDR, MODBUS_READ_HOLDING, gReadSpeed.addr, tmpNum, DEV_SPEED);//REG_FILER_SPEED
      }
    }
    gAppEvent ^= APPEVENT_GET_SPEED_EVT;
  }
  //Read Level
  if(gAppEvent & APPEVENT_GET_LEVEL_EVT){
    ModBus_ReadRegister(C_DEV_LEVEL_ADDR, MODBUS_READ_HOLDING, REG_LEVEL_FILTER, 4, DEV_LEVEL);
    gAppEvent ^= APPEVENT_GET_LEVEL_EVT;
  }
  
  /*******************************************************************************************************/
  //Receive GSM Data
  if(gAppEvent & APPEVENT_REC_GSM_EVT){
    
    HAL_Gsm_ClearBuf();
    HAL_UART_Receive_IT(&huart1, &gGsmRecByte, 1);
    gAppEvent ^= APPEVENT_REC_GSM_EVT;
  }
  //Receive BLE Data
  if(gAppEvent & APPEVENT_REC_BLE_EVT){
    if(gBleRecBuf.rxLen >= BLE_MIN_SIZE){
      tmpCrc = BLE_UartCalcFCS(gBleRecBuf.rxBuf, gBleRecBuf.rxLen-1);
      if((tmpCrc == gBleRecBuf.rxBuf[gBleRecBuf.rxLen-1])&&(gBleRecBuf.rxBuf[0] == BLE_IDX_SOP)){
        BLE_ProcessRecData(&gBleRecBuf.rxBuf[1]);
      }
    }
    HAL_Ble_ClearBuf();
    HAL_UART_Receive_IT(&huart2, &gBleRecByte, 1);
    gAppEvent ^= APPEVENT_REC_BLE_EVT;
  }
  //Receive Bus Data
  if(gAppEvent & APPEVENT_REC_BUS_EVT){
    if(gBusRecBuf.rxLen >= MODBUS_MIN_SIZE){
      tmpCrc = HalUartCalcCrc16(gBusRecBuf.rxBuf, gBusRecBuf.rxLen-2);
      if(tmpCrc == BUILD_UINT16(gBusRecBuf.rxBuf[gBusRecBuf.rxLen-1], gBusRecBuf.rxBuf[gBusRecBuf.rxLen-2])){
        if(gBusRecBuf.rxBuf[0] == gDevInfo.addr){
          if(gBusRecBuf.rxBuf[1] == MODBUS_READ_HOLDING){
            tmpCrc = BUILD_UINT16(gBusRecBuf.rxBuf[5], gBusRecBuf.rxBuf[4]);
            if(tmpCrc > 0){
              ModBus_ProcessReadRegister(&gBusRecBuf.rxBuf[2]);
            }
          }
          else if((gBusRecBuf.rxBuf[1] == MODBUS_WRITE_SINGLE_HOLDING)&&(gBusRecBuf.rxLen == MODBUS_WRITE_SIZE)){
            if(ModBus_ProcessWriteRegister(&gBusRecBuf.rxBuf[2])){
              HAL_Bus_Send(gBusRecBuf.rxBuf, gBusRecBuf.rxLen);
            }
          }
        }
      }
    }
    HAL_Bus_ClearBuf();
    HAL_UART_Receive_IT(&huart3, &gBusRecByte, 1);
    gAppEvent ^= APPEVENT_REC_BUS_EVT;
  }
  //Receive Speed Data
  if(gAppEvent & APPEVENT_REC_SPEED_EVT){
    if(gSpeedRecBuf.rxLen >= MODBUS_MIN_SIZE){
      tmpCrc = HalUartCalcCrc16(gSpeedRecBuf.rxBuf, gSpeedRecBuf.rxLen-2);
      if(tmpCrc == BUILD_UINT16(gSpeedRecBuf.rxBuf[gSpeedRecBuf.rxLen-1], gSpeedRecBuf.rxBuf[gSpeedRecBuf.rxLen-2])){
        if(gSpeedRecBuf.rxBuf[1] == MODBUS_READ_HOLDING){
          if((gReadSpeed.addr == REG_SURFACE_SPEED)&&(gSpeedRecBuf.rxBuf[2] == 4)){//Read Speed
            tmpSpeed = BUILD_UINT32(gSpeedRecBuf.rxBuf[6], gSpeedRecBuf.rxBuf[5],gSpeedRecBuf.rxBuf[4], gSpeedRecBuf.rxBuf[3]);//unit m
            memcpy((void *)&tmpSpeed, &gSpeedRecBuf.rxBuf[3], DATATYPE_UINT32);
  
            tmpSpeed *= 1000;//Unit mm
            if(tmpSpeed < C_SPEED_MIN){
              if(gWaterMinSpeed < C_SPEED_MIN){
                gWaterSpeed = gWaterMinSpeed+g10sRandSpeed;
              }
              else{
                gWaterSpeed = (uint16_t)tmpSpeed;
//                gWaterSpeed = 0;
              }
            }
            else{
              if(tmpSpeed < C_SPEED_MAX){
                if(tmpSpeed > gWaterSpeed){
                  if((tmpSpeed - gWaterSpeed) < C_SPEED_TORENCE){
                    gWaterSpeed = (uint16_t)tmpSpeed;
                  }
                }
                else{
                  if((gWaterSpeed - tmpSpeed) < C_SPEED_TORENCE){
                    gWaterSpeed = (uint16_t)tmpSpeed;
                  }
                }
                if(gSetSpeed.valid){
                  tmpSpeed = gWaterSpeed*gSetSpeed.kspeed+gSetSpeed.cspeed;
                  tmpSpeed /= 10;
                  gWaterSpeed = (uint16_t)tmpSpeed;
                }
              }
            }       
            if(gWaterLevel == 0){
              gWaterSpeed = 0;
            }
          }
          else if((gReadSpeed.addr == REG_SPEED_SENSITIVITY)&&(gSpeedRecBuf.rxBuf[2] == 2)){
            gReadSpeed.sentivity = BUILD_UINT16(gSpeedRecBuf.rxBuf[4], gSpeedRecBuf.rxBuf[3]);
          }
          else if((gReadSpeed.addr == REG_SPEED_ANGLE)&&(gSpeedRecBuf.rxBuf[2] == 2)){
            gReadSpeed.angle = BUILD_UINT16(gSpeedRecBuf.rxBuf[4], gSpeedRecBuf.rxBuf[3]);
          }
          else if((gReadSpeed.addr == REG_SPEED_GAIN)&&(gSpeedRecBuf.rxBuf[2] == 2)){
            gReadSpeed.gain = BUILD_UINT16(gSpeedRecBuf.rxBuf[4], gSpeedRecBuf.rxBuf[3]);
          }
          else if((gReadSpeed.addr == REG_SPEED_POWER)&&(gSpeedRecBuf.rxBuf[2] == 2)){
            gReadSpeed.power = BUILD_UINT16(gSpeedRecBuf.rxBuf[4], gSpeedRecBuf.rxBuf[3]);
          }
          else if((gReadSpeed.addr == REG_FLOW_DIERECTION)&&(gSpeedRecBuf.rxBuf[2] == 2)){
            gReadSpeed.posneg = BUILD_UINT16(gSpeedRecBuf.rxBuf[4], gSpeedRecBuf.rxBuf[3]);
          }
          else if(gWriteSpeed.addr == REG_STRENGTH_SPEED){
            gReadSpeed.strength = BUILD_UINT16(gSpeedRecBuf.rxBuf[4], gSpeedRecBuf.rxBuf[3]);
          }
          else if(gWriteSpeed.addr == REG_SPEED_VERSION){
            memcpy((void *)gReadSpeed.verbuf, (void *)&gSpeedRecBuf.rxBuf[3], 8);
          }
        }
        else if(gSpeedRecBuf.rxBuf[1] == MODBUS_WRITE_SINGLE_HOLDING){
          //01 06 02 xx xx CRC
          if(gWriteSpeed.addr == REG_SPEED_SENSITIVITY){
            gReadSpeed.sentivity = BUILD_UINT16(gSpeedRecBuf.rxBuf[5], gSpeedRecBuf.rxBuf[4]);
            ModBus_WriteHoldingReg(gDevInfo.addr, REG_SPEED_SENSITIVITY, gReadSpeed.sentivity, DEV_BUS);
          }
          else if(gWriteSpeed.addr == REG_SPEED_ANGLE){
            gReadSpeed.angle = BUILD_UINT16(gSpeedRecBuf.rxBuf[5], gSpeedRecBuf.rxBuf[4]);
            ModBus_WriteHoldingReg(gDevInfo.addr, REG_SPEED_ANGLE, gReadSpeed.angle, DEV_BUS);
          }
          else if(gWriteSpeed.addr == REG_SPEED_GAIN){
            gReadSpeed.gain = BUILD_UINT16(gSpeedRecBuf.rxBuf[5], gSpeedRecBuf.rxBuf[4]);
            ModBus_WriteHoldingReg(gDevInfo.addr, REG_SPEED_GAIN, gReadSpeed.gain, DEV_BUS);
          }
          else if(gWriteSpeed.addr == REG_SPEED_POWER){
            gReadSpeed.power = BUILD_UINT16(gSpeedRecBuf.rxBuf[5], gSpeedRecBuf.rxBuf[4]);
            ModBus_WriteHoldingReg(gDevInfo.addr, REG_SPEED_POWER, gReadSpeed.power, DEV_BUS);
          }
          
          tmpBuf[0] = HI_UINT16(gReadSpeed.sentivity);
          tmpBuf[1] = LO_UINT16(gReadSpeed.sentivity);
          tmpBuf[2] = HI_UINT16(gReadSpeed.angle);
          tmpBuf[3] = LO_UINT16(gReadSpeed.angle);
          tmpBuf[4] = HI_UINT16(gReadSpeed.gain);
          tmpBuf[5] = LO_UINT16(gReadSpeed.gain);
          tmpBuf[6] = HI_UINT16(gReadSpeed.power);
          tmpBuf[7] = LO_UINT16(gReadSpeed.power);
          tmpBuf[8] = HI_UINT16(gReadSpeed.strength);//20230909
          tmpBuf[9] = LO_UINT16(gReadSpeed.strength);
          BLE_ProcessSendData(BLE_READ_BIT|BLE_RESPONSE_BIT|BLE_READ_SPEEDPARAM, 10, tmpBuf); 
        }
      }
    }
    HAL_Speed_ClearBuf();
    HAL_UART_Receive_IT(&huart4, &gSpeedRecByte, 1);
    gAppEvent ^= APPEVENT_REC_SPEED_EVT;
  }
  //Receive Level Data
  if(gAppEvent & APPEVENT_REC_LEVEL_EVT){
    if(gLevelRecBuf.rxLen >= MODBUS_MIN_SIZE){
      tmpCrc = HalUartCalcCrc16(gLevelRecBuf.rxBuf, gLevelRecBuf.rxLen-2);
      if(tmpCrc == BUILD_UINT16(gLevelRecBuf.rxBuf[gLevelRecBuf.rxLen-1], gLevelRecBuf.rxBuf[gLevelRecBuf.rxLen-2])){
        if((gLevelRecBuf.rxBuf[1] == MODBUS_READ_HOLDING)&&(gLevelRecBuf.rxBuf[2] == 8)){
          gMeterEmptyLevel = BUILD_UINT16(gLevelRecBuf.rxBuf[6], gLevelRecBuf.rxBuf[5]);//unit mm
          if(gMeterRange > (gMeterEmptyLevel/10)){
            gWaterLevel = gMeterRange-gMeterEmptyLevel/10;//Unit cm
          }
          else{
            gWaterLevel = 0;//unit cm
          }
        }
      }
    }
    HAL_Level_ClearBuf();
    HAL_UART_Receive_IT(&huart5, &gLevelRecByte, 1);
    gAppEvent ^= APPEVENT_REC_LEVEL_EVT;
  }
  
}

/***************************************************************************************************
 * @fn      SPIMgr_CalcFCS
 *
 * @brief   Calculate the FCS of a message buffer by XOR'ing each uint8_t.
 *          Remember to NOT include SOP and FCS fields, so start at the CMD field.
 *
 * @param   uint8_t *msg_ptr - message pointer
 * @param   uint8_t len - length (in uint8_ts) of message
 *
 * @return  result uint8_t
 ***************************************************************************************************/
static uint8_t BLE_UartCalcFCS( uint8_t *msg_ptr, uint8_t len )
{
  uint8_t x;
  uint8_t xorResult;

  xorResult = 0;

  for ( x = 0; x < len; x++, msg_ptr++ )
    xorResult ^= *msg_ptr;

  return ( xorResult );
}
/**
  * @brief TX Transfer Send.
  * @param huart: UART handle.
  * @retval None
  */
uint8_t HAL_GSM_Send( uint8_t *msg, uint8_t len )
{
  uint8_t i;

  for(i = 0;i < 3;i++)
  {
    if(gGsmRecBuf.recData == TRUE)
      uart_delay(50);
    else
    {
      HAL_UART_Transmit(&huart1, msg, len, 100);
      break;
    }
  }
  return SUCCESS;
}
/**
  * @brief TX Transfer BLE Send.
  * @param huart: UART handle.
  * @retval None
  */
uint8_t HAL_BLE_Send( uint8_t *msg, uint8_t len )
{
  uint8_t i;

  for(i = 0;i < 3;i++)
  {
    if(gBleRecBuf.recData == TRUE)
      uart_delay(50);
    else
    {
      HAL_UART_Transmit(&huart2, msg, len, 100);
      break;
    }
  }
  return SUCCESS;
}
/**
  * @brief TX Transfer Bus Send.
  * @param huart: UART handle.
  * @retval None
  */
uint8_t HAL_Bus_Send( uint8_t *msg, uint8_t len )
{
  uint8_t i;

  for(i = 0;i < 3;i++)
  {
    if(gBusRecBuf.recData == TRUE)
      uart_delay(50);
    else
    {
      HAL_GPIO_WritePin(GPIOE, GPIO_PIN_15, GPIO_PIN_SET);
      HAL_UART_Transmit(&huart3, msg, len, 100);
      HAL_GPIO_WritePin(GPIOE, GPIO_PIN_15, GPIO_PIN_RESET);
      break;
    }
  }
  return SUCCESS;
}

/**
  * @brief TX Transfer Speed Send.
  * @param huart: UART handle.
  * @retval None
  */
uint8_t HAL_Speed_Send( uint8_t *msg, uint8_t len )
{
  uint8_t i;

  for(i = 0;i < 3;i++)
  {
    if(gSpeedRecBuf.recData == TRUE)
      uart_delay(50);
    else
    {
      HAL_GPIO_WritePin(GPIOA, GPIO_PIN_15, GPIO_PIN_SET);
      HAL_UART_Transmit(&huart4, msg, len, 100);
      HAL_GPIO_WritePin(GPIOA, GPIO_PIN_15, GPIO_PIN_RESET);
      break;
    }
  }
  return SUCCESS;
}
/**
  * @brief TX Transfer Level Send.
  * @param huart: UART handle.
  * @retval None
  */
uint8_t HAL_Level_Send( uint8_t *msg, uint8_t len )
{
  uint8_t i;

  for(i = 0;i < 3;i++)
  {
    if(gLevelRecBuf.recData == TRUE)
      uart_delay(50);
    else
    {
      HAL_GPIO_WritePin(GPIOD, GPIO_PIN_1, GPIO_PIN_SET);
      HAL_UART_Transmit(&huart5, msg, len, 100);
      HAL_GPIO_WritePin(GPIOD, GPIO_PIN_1, GPIO_PIN_RESET);
      break;
    }
  }
  return SUCCESS;
}
/***************************************************************************************************
 * @fn      HalUartCalcCrc16
 *
 * @brief   Calculate the FCS of a message buffer by XOR'ing each byte.
 *          Remember to NOT include SOP and FCS fields, so start at the CMD field.
 *
 * @param   byte *msg_ptr - message pointer
 * @param   byte len - length (in bytes) of message
 *
 * @return  result byte
 ***************************************************************************************************/
static uint16_t HalUartCalcCrc16( uint8_t *msg_ptr, uint8_t len )
{
	unsigned char uchCRCHi = 0xFF; //
	unsigned char uchCRCLo = 0xFF ; //
	unsigned uIndex ; //

	while (len--) // 
	{
		uIndex = uchCRCHi ^ *msg_ptr++ ; //
		uchCRCHi = uchCRCLo ^ auchCRCHi[uIndex];
		uchCRCLo = auchCRCLo[uIndex] ;
	}
	return((uchCRCHi<< 8) | uchCRCLo);
}
/***************************************************************************************************
 * @fn      BLE_ProcessRecData
 *
 * @brief   Read All Input Register-->period read
 *
 * @param   None
 *
 * @return  None
 ***************************************************************************************************/
static void BLE_ProcessRecData(uint8_t *pBuf)
{//len cmd data crc
  uint8_t tmpBufLen = pBuf[0];
  uint8_t tmpCmd = pBuf[1];
  uint8_t tmpBuf[32],tmpLen;
  uint16_t tmpSpeed;
  uint32_t tmpValue;
  
  if((tmpCmd&0xF0) == BLE_READ_BIT){
    if((tmpCmd&BLE_CMD_MASK) == BLE_SET_SYSTEM){
      tmpBuf[0] = gDevInfo.addr;
      tmpBuf[1] = gDevInfo.baudrate;
      BLE_ProcessSendData(BLE_READ_BIT|BLE_RESPONSE_BIT|BLE_SET_SYSTEM, 2, tmpBuf);
    }
    else if((tmpCmd&BLE_CMD_MASK) == BLE_SET_CANEL){
      tmpBuf[0] = gCanelParam.mode;
      if(gCanelParam.mode == C_CANEL_ROUND){
        tmpBuf[1] = HI_UINT16(gCanelParam.radius);
        tmpBuf[2] = LO_UINT16(gCanelParam.radius);
        tmpLen = 3;
      }
      else if(gCanelParam.mode == C_CANEL_RECTANGLE){
        tmpBuf[1] = HI_UINT16(gCanelParam.recWide);
        tmpBuf[2] = LO_UINT16(gCanelParam.recWide);
        tmpLen = 3;
      }
      else if(gCanelParam.mode == C_CANEL_TRAPEZOID){
        tmpBuf[1] = HI_UINT16(gCanelParam.trapeDown);
        tmpBuf[2] = LO_UINT16(gCanelParam.trapeDown);
        tmpBuf[3] = HI_UINT16(gCanelParam.trapeUp);
        tmpBuf[4] = LO_UINT16(gCanelParam.trapeUp);
        tmpBuf[5] = HI_UINT16(gCanelParam.depth);
        tmpBuf[6] = LO_UINT16(gCanelParam.depth);
        tmpLen = 7;
      }
      else if(gCanelParam.mode == C_CANEL_U){
        tmpBuf[1] = HI_UINT16(gCanelParam.radius);
        tmpBuf[2] = LO_UINT16(gCanelParam.radius);
        tmpBuf[3] = HI_UINT16(gCanelParam.recWide);
        tmpBuf[4] = LO_UINT16(gCanelParam.recWide);
        tmpLen = 5;
      }
      else if(gCanelParam.mode == C_CANEL_AREA){
        tmpBuf[1] = HI_UINT16(gCanelParam.area);
        tmpBuf[2] = LO_UINT16(gCanelParam.area);
        tmpLen = 3;
      }
      BLE_ProcessSendData(BLE_READ_BIT|BLE_RESPONSE_BIT|BLE_SET_CANEL, tmpLen, tmpBuf);
    }
    else if((tmpCmd&BLE_CMD_MASK) == BLE_SET_RANGE){
      tmpBuf[0] = HI_UINT16(gWaterFirstLevel);
      tmpBuf[1] = LO_UINT16(gWaterFirstLevel);
      tmpBuf[2] = HI_UINT16(gMeterRange);
      tmpBuf[3] = LO_UINT16(gMeterRange);
      BLE_ProcessSendData(BLE_READ_BIT|BLE_RESPONSE_BIT|BLE_SET_RANGE, 4, tmpBuf);
    }
    else if((tmpCmd&BLE_CMD_MASK) == BLE_SET_TOLERANCE){
      tmpBuf[0] = HI_UINT16(gMeterLowRange);
      tmpBuf[1] = LO_UINT16(gMeterLowRange);
      BLE_ProcessSendData(BLE_READ_BIT|BLE_RESPONSE_BIT|BLE_SET_TOLERANCE, 2, tmpBuf);
    }
    else if((tmpCmd&BLE_CMD_MASK) == BLE_READ_STATUS){
      tmpBuf[0] = HI_UINT16(gWaterLevel);
      tmpBuf[1] = LO_UINT16(gWaterLevel);
      tmpBuf[2] = HI_UINT16(gMeterEmptyLevel/10);
      tmpBuf[3] = LO_UINT16(gMeterEmptyLevel/10);
      tmpBuf[4] = HI_UINT16(gWaterSpeed);
      tmpBuf[5] = LO_UINT16(gWaterSpeed);
      tmpValue = (uint32_t)(gWaterFlow*100);
      tmpBuf[6] = BREAK_UINT32(tmpValue, 3);
      tmpBuf[7] = BREAK_UINT32(tmpValue, 2);
      tmpBuf[8] = BREAK_UINT32(tmpValue, 1);
      tmpBuf[9] = BREAK_UINT32(tmpValue, 0);

      tmpBuf[10] = BREAK_UINT32(gBleSumFlow, 3);
      tmpBuf[11] = BREAK_UINT32(gBleSumFlow, 2);
      tmpBuf[12] = BREAK_UINT32(gBleSumFlow, 1);
      tmpBuf[13] = BREAK_UINT32(gBleSumFlow, 0);
      
      tmpBuf[14] = BREAK_UINT32(gCanelArea, 3);
      tmpBuf[15] = BREAK_UINT32(gCanelArea, 2);
      tmpBuf[16] = BREAK_UINT32(gCanelArea, 1);
      tmpBuf[17] = BREAK_UINT32(gCanelArea, 0);
    
      BLE_ProcessSendData(BLE_READ_BIT|BLE_RESPONSE_BIT|BLE_READ_STATUS, 18, tmpBuf);
    }
    else if((tmpCmd&BLE_CMD_MASK) == BLE_SET_MINSPEED){
      tmpBuf[0] = HI_UINT16(gWaterMinSpeed);
      tmpBuf[1] = LO_UINT16(gWaterMinSpeed);
      BLE_ProcessSendData(BLE_READ_BIT|BLE_RESPONSE_BIT|BLE_SET_MINSPEED, 2, tmpBuf);
    }
    else if((tmpCmd&BLE_CMD_MASK)==BLE_SET_SPEED){
      tmpBuf[0] = gSetSpeed.valid;
      tmpBuf[1] = HI_UINT16(gSetSpeed.kspeed);
      tmpBuf[2] = LO_UINT16(gSetSpeed.kspeed);
      tmpBuf[3] = HI_UINT16(gSetSpeed.cspeed);
      tmpBuf[4] = LO_UINT16(gSetSpeed.cspeed);
      BLE_ProcessSendData(BLE_READ_BIT|BLE_RESPONSE_BIT|BLE_SET_SPEED, 5, tmpBuf);      
    }
    else if((tmpCmd&BLE_CMD_MASK)==BLE_READ_SPEEDPARAM){
      tmpBuf[0] = HI_UINT16(gReadSpeed.sentivity);
      tmpBuf[1] = LO_UINT16(gReadSpeed.sentivity);
      tmpBuf[2] = HI_UINT16(gReadSpeed.angle);
      tmpBuf[3] = LO_UINT16(gReadSpeed.angle);
      tmpBuf[4] = HI_UINT16(gReadSpeed.gain);
      tmpBuf[5] = LO_UINT16(gReadSpeed.gain);
      tmpBuf[6] = HI_UINT16(gReadSpeed.power);
      tmpBuf[7] = LO_UINT16(gReadSpeed.power);
      tmpBuf[8] = HI_UINT16(gReadSpeed.strength);//20230909
      tmpBuf[9] = LO_UINT16(gReadSpeed.strength);
      BLE_ProcessSendData(BLE_READ_BIT|BLE_RESPONSE_BIT|BLE_READ_SPEEDPARAM, 10, tmpBuf);  
    }
    else if((tmpCmd&BLE_CMD_MASK)==BLE_SYSTEM_VERSION){
      memcpy(tmpBuf, c_version, c_ver_num);
      memcpy(&tmpBuf[c_ver_num], gReadSpeed.verbuf, 8);//20230909
      BLE_ProcessSendData(BLE_READ_BIT|BLE_RESPONSE_BIT|BLE_SYSTEM_VERSION, c_ver_num+8, tmpBuf);
    }
    else if((tmpCmd&BLE_CMD_MASK)==BLE_READ_POSNEG){
      tmpBuf[0] = HI_UINT16(gReadSpeed.posneg);
      tmpBuf[1] = LO_UINT16(gReadSpeed.posneg);
      BLE_ProcessSendData(BLE_READ_BIT|BLE_RESPONSE_BIT|BLE_READ_POSNEG, 2, tmpBuf);
    }
  }
  else if((tmpCmd&0xF0) == 0x00){
    if((tmpCmd&BLE_CMD_MASK) == BLE_SET_SYSTEM){
      if(gDevInfo.addr != pBuf[2]){
        gDevInfo.addr = pBuf[2];
      }
      if(gDevInfo.baudrate != pBuf[3]){
        gDevInfo.baudrate = pBuf[3];
        MX_USART3_UART_Init(gDevInfo.baudrate);
      }
      Flash_ChangeSystemInformation(SYSTEM_DEVICE_INFO_OFFSET, SYSTEM_DEVICE_INFO_SIZE, (uint8_t *)&gDevInfo); 
    }
    else if((tmpCmd&BLE_CMD_MASK) == BLE_SET_CANEL){
      gCanelParam.mode = pBuf[2];
      if(gCanelParam.mode == C_CANEL_ROUND){
        gCanelParam.radius = BUILD_UINT16(pBuf[4],pBuf[3]);
      }
      else if(gCanelParam.mode == C_CANEL_RECTANGLE){
        gCanelParam.recWide = BUILD_UINT16(pBuf[4],pBuf[3]);
      }
      else if(gCanelParam.mode == C_CANEL_TRAPEZOID){
        gCanelParam.trapeDown = BUILD_UINT16(pBuf[4],pBuf[3]);
        gCanelParam.trapeUp = BUILD_UINT16(pBuf[6],pBuf[5]);
        gCanelParam.depth = BUILD_UINT16(pBuf[8],pBuf[7]);
      }
      else if(gCanelParam.mode == C_CANEL_U){
        gCanelParam.radius = BUILD_UINT16(pBuf[4],pBuf[3]);
        gCanelParam.recWide = BUILD_UINT16(pBuf[6],pBuf[5]);
      }
      else if(gCanelParam.mode == C_CANEL_AREA){
        gCanelParam.area = BUILD_UINT16(pBuf[4],pBuf[3]);
      }
      Flash_ChangeSystemInformation(SYSTEM_DEVICE_CANEL_OFFSET, SYSTEM_DEVICE_CANEL_SIZE, (uint8_t *)&gCanelParam);
    }
    else if((tmpCmd&BLE_CMD_MASK) == BLE_SET_RANGE){
      gWaterFirstLevel = BUILD_UINT16(pBuf[3],pBuf[2]);
      gMeterRange = gWaterFirstLevel+gMeterEmptyLevel/10;//UNIT cm
      tmpBuf[0]= pBuf[2];tmpBuf[1]= pBuf[3];
      tmpBuf[2]= HI_UINT16(gMeterRange);tmpBuf[3]= LO_UINT16(gMeterRange);
      Flash_ChangeSystemInformation(SYSTEM_DEVICE_RANGE_OFFSET, SYSTEM_DEVICE_RANGE_SIZE, (uint8_t *)tmpBuf); 
    }
    else if((tmpCmd&BLE_CMD_MASK) == BLE_SET_TOLERANCE){
      gMeterLowRange = BUILD_UINT16(pBuf[3],pBuf[2]);
      Flash_ChangeSystemInformation(SYSTEM_DEVICE_LOWRANGE_OFFSET, SYSTEM_DEVICE_LOWRANGE_SIZE, (uint8_t *)&gMeterLowRange);
    }
    else if((tmpCmd&BLE_CMD_MASK) == BLE_CLEAR_FLOW){
      if((tmpBufLen == 1)||(tmpBufLen == 5)){
        if(tmpBufLen == 1){
          gWaterSumFlow = 0;
          gSumFlow = 0;
          gBleSumFlow = 0;
        }
        else if(tmpBufLen == 5){
          gWaterSumFlow = BUILD_UINT32(pBuf[5],pBuf[4],pBuf[3],pBuf[2]);
          gSumFlow = gWaterSumFlow;
          gBleSumFlow = gWaterSumFlow;
        }
        Flash_ChangeSystemInformation(SYSTEM_DEVICE_FLOW_OFFSET, SYSTEM_DEVICE_FLOW_SIZE, (uint8_t *)&gWaterSumFlow); 
      }
    }
    else if((tmpCmd&BLE_CMD_MASK) == BLE_SET_MINSPEED){
      tmpSpeed = BUILD_UINT16(pBuf[3],pBuf[2]);
//      if(tmpSpeed < C_SPEED_MIN)
      {
        gWaterMinSpeed = tmpSpeed;
        Flash_ChangeSystemInformation(SYSTEM_DEVICE_MIN_SPEED_OFFSET, SYSTEM_DEVICE_MIN_SPEED_SIZE, (uint8_t *)&gWaterMinSpeed);
      }
    }
    else if((tmpCmd&BLE_CMD_MASK) == BLE_SET_SPEED){
      gSetSpeed.valid = pBuf[2];
      gSetSpeed.kspeed = BUILD_UINT16(pBuf[4],pBuf[3]);
      gSetSpeed.cspeed = BUILD_UINT16(pBuf[6],pBuf[5]);
      Flash_ChangeSystemInformation(SYSTEM_DEVICE_SETSPEED_OFFSET, SYSTEM_DEVICE_SETSPEED_SIZE, (uint8_t *)&gSetSpeed); 
    }
    else if((tmpCmd&BLE_CMD_MASK)==BLE_SET_SPEEDPARAM){
      gReadSpeed.idx = 0;//now to write data
      gWriteSpeed.flag = 1;
      gWriteSpeed.addr = BUILD_UINT16(pBuf[3],pBuf[2]);
      gWriteSpeed.dat = BUILD_UINT16(pBuf[5],pBuf[4]);
    }
  }
}
/***************************************************************************************************
 * @fn      BLE_ProcessSendData
 *
 * @brief   Read All Input Register-->period read
 *
 * @param   None
 *
 * @return  None
 ***************************************************************************************************/
static void BLE_ProcessSendData(uint8_t cmd, uint8_t len, uint8_t *pBuf)
{//02 len cmd data crc
  uint8_t tmpBuf[32];
  uint8_t *p = tmpBuf;
  
  *p++ = BLE_IDX_SOP;
  *p++ = len+1;//-skip
  *p++ = cmd;
  if((BLE_MIN_SIZE+len+1) < 32){
    memcpy(p, pBuf, len);
    p += len;
  }
  *p++ = HalUartCalcCrc16(tmpBuf, BLE_MIN_SIZE+len-1);
  HAL_BLE_Send(tmpBuf, BLE_MIN_SIZE+len);
}
/***************************************************************************************************
 * @fn      ModBus_ProcessReadRegister
 *
 * @brief   Read All Input Register-->period read
 *
 * @param   None
 *
 * @return  None
 ***************************************************************************************************/
float tmpRec,tmpRound,tmpTrapezoid;
static void ModBus_CalculateFlow(void)
{
  float tmpArea;
  float tmpDepth;
  float tmpQ,tmpH;
  uint32_t tmpWaterFlow;
  
  if(gCanelParam.mode <= C_CANEL_AREA){
    if(gCanelParam.mode == C_CANEL_ROUND){
      tmpRound = C_PI*gCanelParam.radius*gCanelParam.radius;//Unit cm
//      tmpRound *= gCanelParam.radius;
      tmpRound /= 10000;//Unit m
      
      tmpArea = tmpRound;//Store Area Unit m
      tmpArea *= 100;
      gCanelArea = (uint32_t)tmpArea;
      
      tmpRound *= gWaterSpeed;//Unit mm
      tmpRound /= 1000;//Unit m
      gWaterFlow = tmpRound;
      gSumFlow += C_CALCULATE_PERIOD*tmpRound;
    }
    else if(gCanelParam.mode == C_CANEL_RECTANGLE){
      if(gMeterRange >= (gMeterEmptyLevel/10)){
        tmpRec = gMeterRange - gMeterEmptyLevel/10;//Unit cm
        tmpRec /= 100;//Unit m
        tmpRec *= gCanelParam.recWide;//Area Unit cm
        tmpRec /= 100;//Unit m
        
        tmpArea = tmpRec;//Store Area Unit m
        tmpArea *= 100;
        gCanelArea = (uint32_t)tmpArea;
        
        tmpRec *= gWaterSpeed;
        tmpRec /= 1000;//Unit m
        gWaterFlow = tmpRec;
        gSumFlow += C_CALCULATE_PERIOD*tmpRec;
      }
    }
    else if(gCanelParam.mode == C_CANEL_TRAPEZOID){
      if(gMeterRange >= (gMeterEmptyLevel/10)){
        if(gCanelParam.depth > 0){
          tmpDepth = gMeterRange - gMeterEmptyLevel/10;//Unit cm
          if(gCanelParam.trapeUp > gCanelParam.trapeDown){
            tmpTrapezoid = gCanelParam.trapeUp-gCanelParam.trapeDown;
            tmpRec = tmpDepth/gCanelParam.depth;
            tmpRec *= tmpTrapezoid;
            tmpRec += 2*gCanelParam.trapeDown;//Up+Down
          }
          else{
            tmpTrapezoid = gCanelParam.trapeDown-gCanelParam.trapeUp;
            tmpRec = (gCanelParam.depth-tmpDepth)/gCanelParam.depth;
            tmpRec *= tmpTrapezoid;
            tmpRec += gCanelParam.trapeDown+gCanelParam.trapeUp;//Up+Down
          }
          tmpRec *= tmpDepth;//*h
          tmpRec /= 2;// *1/2
          
          tmpRec /= 10000;//Unit m
          
          tmpArea = tmpRec;//Store Area Unit m
          tmpArea *= 100;
          gCanelArea = (uint32_t)tmpArea;
          
          tmpRec *= gWaterSpeed;//Unit mm
          tmpRec /= 1000;//Unit m
          gWaterFlow = tmpRec;
          gSumFlow += C_CALCULATE_PERIOD*tmpRec;
        }
      }
    }
    else if(gCanelParam.mode == C_CANEL_U){
      if(gMeterRange > ((gMeterEmptyLevel/10+gCanelParam.radius))){
        tmpRec = gMeterRange - gMeterEmptyLevel/10-gCanelParam.radius;//Unit cm
        tmpRec /= 100;//Unit m
        tmpRec *= 2*gCanelParam.radius;//Area Unit cm
        tmpRec /= 100;//Unit m
        
        tmpRound = C_PI;
        tmpRound *= gCanelParam.radius*gCanelParam.radius;//Unit cm
        tmpRound /= 10000;//Unit m
        tmpRound /= 2;//half round
        
        tmpRec += tmpRound;
        
        tmpArea = tmpRec;//Store Area Unit m
        tmpArea *= 100;
        gCanelArea = (uint32_t)tmpArea;
        
        tmpRec *= gWaterSpeed;//Unit mm
        tmpRec /= 1000;//Unit m
        gWaterFlow = tmpRec;
        gSumFlow += C_CALCULATE_PERIOD*tmpRec;
      }
      else{
        tmpRec = gMeterRange - gMeterEmptyLevel/10;
        tmpH = gCanelParam.radius - tmpRec;//Unit cm=h
        tmpQ = acos(tmpH/gCanelParam.radius)*180/C_PI;//
        tmpRec = C_PI*gCanelParam.radius*gCanelParam.radius;
        tmpRec = tmpRec*tmpQ/180;//tmpRec*2*tmpQ/360 unit cm2
        
        tmpQ = gCanelParam.radius*sin(tmpQ*C_PI/180)*tmpH;//2*gCanelParam.radius*sin(tmpQ)*tmpH/2; Unit cm2
        tmpRec -= tmpQ;//Unit cm2
        tmpRec /= 10000UL;//Unit m2
        
        tmpArea = tmpRec;//Store Area Unit m
        tmpArea *= 100;
        gCanelArea = (uint32_t)tmpArea;
        
        tmpRec *= gWaterSpeed;//Unit mm
        tmpRec /= 1000;//Unit m
        gWaterFlow = tmpRec;
        gSumFlow += C_CALCULATE_PERIOD*tmpRec;
      }
    }
    else if(gCanelParam.mode == C_CANEL_AREA){
      tmpRec = gCanelParam.area;
      
      tmpArea = tmpRec;//Store Area Unit m
      tmpArea *= 100;
      gCanelArea = (uint32_t)tmpArea;
      
      tmpRec *= gWaterSpeed;//Unit mm
      tmpRec /= 1000;//Unit m
      gWaterFlow = tmpRec;
      gSumFlow += C_CALCULATE_PERIOD*tmpRec;
    }
//    if((gWaterLevel > 6000)&&(gWaterFlow == 0)){//Reset
//      while(1);
//    }
    memcpy((void *)&tmpWaterFlow, (void *)&gWaterFlow, DATATYPE_UINT32);
    gHiWaterFlow = tmpWaterFlow>>16;
    gLoWaterFlow = tmpWaterFlow&0xFFFF;
    
    if(gSumFlow > 0xFFFFFFFF){
      tmpArea = gSumFlow;
      while(1){
        tmpArea -= 0xFFFFFFFF;
        if(tmpArea < 0xFFFFFFFF){
          gWaterSumFlow = (uint32_t)tmpArea;
          break;
        }
      }
    }
    else{
      gWaterSumFlow = (uint32_t)gSumFlow;
    }
    gHiWaterSumFlow = gWaterSumFlow>>16;
    gLoWaterSumFlow = gWaterSumFlow&0xFFFF;
    
    gBleSumFlow = gWaterSumFlow;//(uint32_t)(10*gSumFlow); //20230909
  }
}


/***************************************************************************************************
 * @fn      ModBus_ProcessReadRegister
 *
 * @brief   Read All Input Register-->period read
 *
 * @param   None
 *
 * @return  None
 ***************************************************************************************************/
static void ModBus_ProcessReadRegister(uint8_t *pBuf)
{//01 03 num data crc
  uint8_t i,tmpLen=0,tmpFlag=0;
  uint16_t tmpReg,tmpCnt,tmpStart,tmpValue;
  uint8_t tmpBuf[64];
  uint8_t *p = tmpBuf;
  uint32_t tmpFloat;
  
  tmpReg = BUILD_UINT16(pBuf[1], pBuf[0]);
  tmpStart = tmpReg;
  tmpCnt = BUILD_UINT16(pBuf[3], pBuf[2]);
  tmpCnt -= 1;
  
  *p++ = gDevInfo.addr;
  *p++ = MODBUS_READ_HOLDING;
  p++;//skip num
  for(i = 0;i < C_MODBUS_ATTR_SIZE;i++){
    if(tmpReg == ModBus_Attrs[i].reg){
      /*if(tmpReg == REG_BUS_LEVEL){
        tmpValue = 10*gMeterRange-gMeterEmptyLevel;
        tmpValue /= 10;
        *p++ = HI_UINT16(tmpValue);
        *p++ = LO_UINT16(tmpValue);
//        p += 2;
        tmpLen += 2;
      }
      else*/
      {
        if(ModBus_Attrs[i].dataType == DATATYPE_UINT8){
          *p++ = 0;
          memcpy(p, ModBus_Attrs[i].dataPtr, DATATYPE_UINT8);
          *p++;
          tmpLen += ModBus_Attrs[i].dataType+1;
//          p += ModBus_Attrs[i].dataType+1;
        }
        else if(ModBus_Attrs[i].dataType == DATATYPE_UINT16){
          memcpy((void *)&tmpValue, ModBus_Attrs[i].dataPtr, DATATYPE_UINT16);
          *p++ = HI_UINT16(tmpValue);
          *p++ = LO_UINT16(tmpValue);
          tmpLen += 2;
//          p += 2;
        }
        else if(ModBus_Attrs[i].dataType == DATATYPE_UINT32){
//          tmpFloat = *((uint8_t *)ModBus_Attrs[i].dataPtr);
          memcpy((void *)&tmpFloat, ModBus_Attrs[i].dataPtr, DATATYPE_UINT32);
          *p++ = BREAK_UINT32(tmpFloat, 3);
          *p++ = BREAK_UINT32(tmpFloat, 2);
          *p++ = BREAK_UINT32(tmpFloat, 1);
          *p++ = BREAK_UINT32(tmpFloat, 0);
          tmpLen += 4;
//          p += 4;
        }
      }
      if(tmpReg < (tmpStart+tmpCnt)){
        tmpReg++;
      }
      else{
        break;
      }
      tmpFlag = 1;
    }
    else{
      if(tmpFlag)break;
    }
  }
  if(tmpLen > 0){
    tmpBuf[2] = tmpLen;
    tmpCnt = HalUartCalcCrc16(tmpBuf, tmpLen+3);
    tmpBuf[tmpLen+3] = HI_UINT16(tmpCnt);
    tmpBuf[tmpLen+4] = LO_UINT16(tmpCnt);
    HAL_Bus_Send(tmpBuf, tmpLen+5);
  }
}
/***************************************************************************************************
 * @fn      ModBus_ProcessWriteRegister
 *
 * @brief   Read All Input Register-->period read
 *
 * @param   None
 *
 * @return  None
 ***************************************************************************************************/

static uint8_t ModBus_ProcessWriteRegister(uint8_t *pBuf)
{
  uint8_t tmpBuf[8];
  uint8_t tmpFlag = 0;
  uint16_t tmpReg;
  
  tmpReg = BUILD_UINT16(pBuf[1], pBuf[0]);
//  modBusData = BUILD_UINT16(pBuf[3], pBuf[2]);
  
  if(tmpReg == REG_BUS_CLEAR_FLOW){
    gWaterSumFlow = 0;
    gSumFlow = 0;
    gBleSumFlow = 0;
    Flash_ChangeSystemInformation(SYSTEM_DEVICE_FLOW_OFFSET, SYSTEM_DEVICE_FLOW_SIZE, (uint8_t *)&gWaterSumFlow); 
    tmpFlag = 1;
    return tmpFlag;
  }
  if(tmpReg == REG_BUS_DEVADDR){
    gDevInfo.addr = pBuf[3];
    tmpFlag = 1;
  }
  else if(tmpReg == REG_BUS_BAUDRATE){
    gDevInfo.baudrate = pBuf[3];
    tmpFlag = 1;
  }
  else if(tmpReg == REG_BUS_CNL_MODE){
    gCanelParam.mode = pBuf[3];
    tmpFlag = 1;
  }
  else if(tmpReg == REG_BUS_CNL_R){
    gCanelParam.radius = BUILD_UINT16(pBuf[3], pBuf[2]);
    tmpFlag = 1;
  }
  else if(tmpReg == REG_BUS_CNL_RECTWIDE){
    gCanelParam.recWide = BUILD_UINT16(pBuf[3], pBuf[2]);
    tmpFlag = 1;
  }
  else if(tmpReg == REG_BUS_CNL_TRAPEZIUM_1WIDE){
    gCanelParam.trapeDown = BUILD_UINT16(pBuf[3], pBuf[2]);
    tmpFlag = 1;
  }
  else if(tmpReg == REG_BUS_CNL_TRAPEZIUM_2WIDE){
    gCanelParam.trapeUp = BUILD_UINT16(pBuf[3], pBuf[2]);
    tmpFlag = 1;
  }
  else if(tmpReg == REG_BUS_CNL_TRAPEZIUM_DEPTH){
    gCanelParam.depth = BUILD_UINT16(pBuf[3], pBuf[2]);
    tmpFlag = 1;
  }
  else if(tmpReg == REG_BUS_FIRST_LEVEL){
    gWaterFirstLevel = BUILD_UINT16(pBuf[3],pBuf[2]);
    gMeterRange = gWaterFirstLevel+gMeterEmptyLevel/10;//UNIT cm
    tmpFlag = 1;
  }
  else if(tmpReg == REG_BUS_RANGE){
    gMeterRange = BUILD_UINT16(pBuf[3], pBuf[2]);
    tmpFlag = 1;
  }
  else if(tmpReg == REG_BUS_LOW_RANGE){
    gMeterLowRange = BUILD_UINT16(pBuf[3], pBuf[2]);
    tmpFlag = 1;
  }
  else if(tmpReg == REG_BUS_RANGE_TOLERANCE){
    gFlowTolerance = BUILD_UINT16(pBuf[3], pBuf[2]);
    tmpFlag = 1;
  }
  else if((tmpReg == REG_SPEED_SENSITIVITY)||(tmpReg == REG_SPEED_ANGLE)||
          (tmpReg == REG_SPEED_GAIN)||(tmpReg == REG_SPEED_POWER)){//Set Speed
    tmpFlag = 0;
    gReadSpeed.idx = 0;//now to write data
    gWriteSpeed.flag = 1;
    gWriteSpeed.addr = tmpReg;
    gWriteSpeed.dat = BUILD_UINT16(pBuf[3],pBuf[2]);
  }

//  for(i = 0;i < C_MODBUS_ATTR_SIZE;i++){
//    if(tmpReg == ModBus_Attrs[i].reg){
//      if(ModBus_Attrs[i].accessControl & ACCESS_CONTROL_WRITE){
//        memcpy(ModBus_Attrs[i].dataPtr, &modBusData, ModBus_Attrs[i].dataType);
//        tmpFlag = 1;
//      }
//    }
//  }
  
  if((tmpReg == REG_BUS_DEVADDR)||(tmpReg == REG_BUS_BAUDRATE)){
    Flash_ChangeSystemInformation(SYSTEM_DEVICE_INFO_OFFSET, SYSTEM_DEVICE_INFO_SIZE, (uint8_t *)&gDevInfo); 
    if(tmpReg == REG_BUS_BAUDRATE){
      MX_USART3_UART_Init(gDevInfo.baudrate);
    }
  }
  else if((tmpReg == REG_BUS_CNL_MODE)||(tmpReg == REG_BUS_CNL_R)||
          (tmpReg == REG_BUS_CNL_RECTWIDE)||(tmpReg == REG_BUS_CNL_TRAPEZIUM_1WIDE)||
          (tmpReg == REG_BUS_CNL_TRAPEZIUM_2WIDE)||(tmpReg == REG_BUS_CNL_TRAPEZIUM_DEPTH)){
    Flash_ChangeSystemInformation(SYSTEM_DEVICE_CANEL_OFFSET, SYSTEM_DEVICE_CANEL_SIZE, (uint8_t *)&gCanelParam);    
  }
  else if(tmpReg == REG_BUS_FIRST_LEVEL) {
    tmpBuf[0]= HI_UINT16(gWaterFirstLevel);
    tmpBuf[1]= LO_UINT16(gWaterFirstLevel);
    tmpBuf[2]= HI_UINT16(gMeterRange);
    tmpBuf[3]= LO_UINT16(gMeterRange);
    Flash_ChangeSystemInformation(SYSTEM_DEVICE_RANGE_OFFSET, SYSTEM_DEVICE_RANGE_SIZE, (uint8_t *)tmpBuf); 
  }
  else if(tmpReg == REG_BUS_RANGE) {
    Flash_ChangeSystemInformation(SYSTEM_DEVICE_RANGE_OFFSET, SYSTEM_DEVICE_RANGE_SIZE, (uint8_t *)&gMeterRange); 
  }
  else if(tmpReg == REG_BUS_LOW_RANGE) {
    Flash_ChangeSystemInformation(SYSTEM_DEVICE_LOWRANGE_OFFSET, SYSTEM_DEVICE_LOWRANGE_SIZE, (uint8_t *)&gMeterLowRange); 
  }
  else if(tmpReg == REG_BUS_RANGE_TOLERANCE) {
    Flash_ChangeSystemInformation(SYSTEM_DEVICE_TOLERANCE_OFFSET, SYSTEM_DEVICE_TOLERANCE_SIZE, (uint8_t *)&gFlowTolerance); 
  }
  return tmpFlag;
}
/***************************************************************************************************
 * @fn      ModBus_ReadRegister
 *
 * @brief   Read All Input Register-->period read
 *
 * @param   None
 *
 * @return  None
 ***************************************************************************************************/
static void ModBus_ReadRegister(uint8_t addr, uint8_t cmd, uint16_t regAddr, uint8_t num, uint8_t dev)
{	
	uint8_t tmpBuf[8];
	uint16_t tmpcrc;
	
	tmpBuf[0] = addr;
	tmpBuf[1] = cmd;
	tmpBuf[2] = HI_UINT16(regAddr);
	tmpBuf[3] = LO_UINT16(regAddr);
	tmpBuf[4] = 0x00;
	tmpBuf[5] = num;
	tmpcrc = HalUartCalcCrc16(tmpBuf, 6);
	tmpBuf[6] = HI_UINT16(tmpcrc);
	tmpBuf[7] = LO_UINT16(tmpcrc);
  if(dev == DEV_SPEED){
    HAL_Speed_Send(tmpBuf, 8);
  }
  else if(dev == DEV_LEVEL){
    HAL_Level_Send(tmpBuf, 8);
  }
}
/***************************************************************************************************
 * @fn      ModBus_WriteHoldingReg
 *
 * @brief   Write Holding Register
 *
 * @param   addr ->1-16-->0000-0007 and 0100- 0107 
 *
 * @return  None
 ***************************************************************************************************/
static void ModBus_WriteHoldingReg(uint8_t addr, uint16_t regAddr, uint16_t dat, uint8_t dev)
{
	uint8_t tmpBuf[8];
	uint16_t tmpcrc;
	
	tmpBuf[0] = addr;
	tmpBuf[1] = MODBUS_WRITE_SINGLE_HOLDING;
	tmpBuf[2] = HI_UINT16(regAddr);
	tmpBuf[3] = LO_UINT16(regAddr);
  tmpBuf[4] = HI_UINT16(dat);
	tmpBuf[5] = LO_UINT16(dat);
	tmpcrc = HalUartCalcCrc16(tmpBuf, 6);
	tmpBuf[6] = HI_UINT16(tmpcrc);
	tmpBuf[7] = LO_UINT16(tmpcrc);
  
	if(dev == DEV_SPEED){
    HAL_Speed_Send(tmpBuf, 8);
  }
  else if(dev == DEV_LEVEL){
    HAL_Level_Send(tmpBuf, 8);
  }
  else if(dev == DEV_BUS){
    HAL_Bus_Send(tmpBuf, 8);
  }
}
/***************************************************************************************************
 * @fn      ModBus_SwitchToModBus
 *
 * @brief   Switch to ModBus
 *
 * @param   None
 *
 * @return  None
 ***************************************************************************************************/
static void ModBus_SpeedSwitchToModBus(void)
{
	HAL_Speed_Send((uint8_t *)c_speed_modbus, 11);
}
/* USER CODE END 1 */

/**
  * @}
  */

/**
  * @}
  */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
